package com.imooc.pay.config.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.annotation.Resource;
import java.io.IOException;

@Configuration
public class SqlSessionFactoryConfig {

    @Resource(name = "datasource")
    private ComboPooledDataSource dataSource;

    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;

    @Value("${mybatis.config-location}")
    private String mybatis_config_locations;

    private PathMatchingResourcePatternResolver PMRPR;

    private PathMatchingResourcePatternResolver getPMRPR() {
        if (PMRPR == null) {
            PMRPR = new PathMatchingResourcePatternResolver();
        }
        return PMRPR;
    }

    private String getMapperLocations() {
        return ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperLocations;
    }

    @Bean(name = "sessionFactory")
    public SqlSessionFactoryBean getSqlSessionFactory() throws IOException {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setConfigLocation(new ClassPathResource(mybatis_config_locations));
        sessionFactory.setMapperLocations(getPMRPR().getResources(this.getMapperLocations()));
        return sessionFactory;
    }
}
